{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import argparse\n",
    "import os\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.pyplot import imshow\n",
    "import scipy.io\n",
    "import scipy.misc\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import PIL\n",
    "import tensorflow as tf\n",
    "from keras import backend as K\n",
    "from keras.layers import Input, Lambda, Conv2D\n",
    "from keras.models import load_model, Model\n",
    "from yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes, scale_boxes\n",
    "from yad2k.models.keras_yolo import yolo_head, yolo_boxes_to_corners, preprocess_true_boxes, yolo_loss, yolo_body\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# GRADED FUNCTION: yolo_filter_boxes  \n",
    "\n",
    "def yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = .6):\n",
    "    \"\"\"Filters YOLO boxes by thresholding on object and class confidence.\n",
    "    通过阈值过滤对象和分类的置信度，即去掉置信度pc<阈值threshold的锚框\n",
    "    Arguments:\n",
    "    box_confidence -- tensor of shape (19, 19, 5, 1) 19*19网格中每个网格对应的5个锚框的pc\n",
    "    boxes -- tensor of shape (19, 19, 5, 4)  4=（px,py,ph,pw ）\n",
    "    box_class_probs -- tensor of shape (19, 19, 5, 80) 80种对象( c1,c2,c3，···，c80 )\n",
    "    threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box \n",
    "    \n",
    "    Returns:\n",
    "    scores -- tensor of shape (None,), containing the class probability score for selected boxes\n",
    "    保留了的锚框的pc\n",
    "    boxes -- tensor of shape (None, 4), containing (b_x, b_y, b_h, b_w) coordinates of selected boxes\n",
    "    保留了的锚框的(b_x, b_y, b_h, b_w)\n",
    "    classes -- tensor of shape (None,), containing the index of the class detected by the selected boxes\n",
    "    保留了的锚框的索引\n",
    "    \n",
    "    Note: \"None\" is here because you don't know the exact number of selected boxes, as it depends on the threshold. \n",
    "    For example, the actual output size of scores would be (10,) if there are 10 boxes.\n",
    "    \"\"\"\n",
    "    \n",
    "    ### START CODE HERE ### (≈ 1 line)\n",
    "    box_scores = box_confidence*box_class_probs # shape=(19,19,5,80), pc * ( c1,c2,c3，···，c80 )\n",
    "    ### END CODE HERE ###\n",
    "\n",
    "    # Step 2: Find the box_classes thanks to the max box_scores, keep track of the corresponding score\n",
    "    ### START CODE HERE ### (≈ 2 lines)\n",
    "    box_classes = K.argmax(box_scores, axis=-1) #(19, 19, 5) 返回指定轴的最大值的索引，axis=-1为最后一个维度\n",
    "    box_class_scores = K.max(box_scores, axis=-1) #返回指定轴的最大值所在的向量, shape=(19,19,5) 最后一个维度为 pc*ci \n",
    "    ### END CODE HERE ###\n",
    "\n",
    "    # Step 3: Create a filtering mask based on \"box_class_scores\" by using \"threshold\". The mask should have the\n",
    "    # same dimension as box_class_scores, and be True for the boxes you want to keep (with probability >= threshold)\n",
    "    #根据阈值创建掩码\n",
    "    ### START CODE HERE ### (≈ 1 line)\n",
    "    filtering_mask = box_class_scores >= threshold  # (19,19,5)  >threshold 的为1，否则为0\n",
    "    ### END CODE HERE ###\n",
    "\n",
    "    # Step 4: Apply the mask to scores, boxes and classes\n",
    "    ### START CODE HERE ### (≈ 3 lines)\n",
    "    scores = tf.boolean_mask(box_class_scores, filtering_mask) # 匹配，降到3-1=2维，数组   (?,)\n",
    "    boxes = tf.boolean_mask(boxes, filtering_mask) # (?, 4) 降到4-1=3维矩阵\n",
    "    classes = tf.boolean_mask(box_classes, filtering_mask) # (?,) 降到3-1=2维\n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    print(\"box_scores,\"+str(box_scores.shape))\n",
    "    print(\"box_classes,\"+str(box_classes.shape))\n",
    "    print(\"box_class_scores,\"+str(box_class_scores.shape))\n",
    "    print(\"filtering_mask,\"+str(filtering_mask.shape))\n",
    "    print(\"scores,\"+str(scores.shape))\n",
    "    print(\"boxes,\"+str(boxes.shape))\n",
    "    print(\"classes,\"+str(classes.shape))\n",
    "    \n",
    "    return scores, boxes, classes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#test\n",
    "with tf.Session() as test_a:\n",
    "    box_confidence = tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1)\n",
    "    boxes = tf.random_normal([19, 19, 5, 4], mean=1, stddev=4, seed = 1)\n",
    "    box_class_probs = tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1)\n",
    "    scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = 0.5)\n",
    "    print(\"scores = \" + str(scores.eval()))\n",
    "    print(\"boxes = \" + str(boxes.eval()))\n",
    "    print(\"classes = \" + str(classes.eval()))\n",
    "    print(\"scores[2] = \" + str(scores[2].eval()))\n",
    "    print(\"boxes[2] = \" + str(boxes[2].eval()))\n",
    "    print(\"classes[2] = \" + str(classes[2].eval()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# GRADED FUNCTION: iou\n",
    "\n",
    "def iou(box1, box2):\n",
    "    \"\"\"Implement the intersection over union (IoU) between box1 and box2\n",
    "    交并比\n",
    "    Arguments:\n",
    "    box1 -- first box, list object with coordinates (x1, y1, x2, y2)\n",
    "    box2 -- second box, list object with coordinates (x1, y1, x2, y2)\n",
    "    \"\"\"\n",
    "\n",
    "    # Calculate the (y1, x1, y2, x2) coordinates of the intersection of box1 and box2. Calculate its Area.\n",
    "    ### START CODE HERE ### (≈ 5 lines)\n",
    "    xi1 = max(box1[0],box2[0])\n",
    "    yi1 = max(box1[1],box2[1])\n",
    "    xi2 = min(box1[2],box2[2])\n",
    "    yi2 = min(box1[3],box2[3])\n",
    "    inter_area = (yi2-yi1)*(xi2-xi1) #交集\n",
    "    ### END CODE HERE ###    \n",
    "\n",
    "    # Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)\n",
    "    ### START CODE HERE ### (≈ 3 lines)\n",
    "    box1_area = (box1[2]-box1[0])*(box1[3]-box1[1])\n",
    "    box2_area = (box2[2]-box2[0])*(box2[3]-box2[1])\n",
    "    union_area = box1_area + box2_area - inter_area #并集\n",
    "    ### END CODE HERE ###\n",
    "\n",
    "    # compute the IoU\n",
    "    ### START CODE HERE ### (≈ 1 line)\n",
    "    iou = inter_area / union_area\n",
    "    ### END CODE HERE ###\n",
    "    return iou"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "box1 = (2, 1, 4, 3)\n",
    "box2 = (1, 2, 3, 4) \n",
    "print(\"iou = \" + str(iou(box1, box2)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# GRADED FUNCTION: yolo_non_max_suppression\n",
    "\n",
    "def yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5):\n",
    "    \"\"\"\n",
    "    Applies Non-max suppression (NMS) to set of boxes\n",
    "    对同一辆车，有多个锚框包含它，使用非最大值抑制，取\n",
    "    Arguments:\n",
    "    scores - tensor类型，维度为(None,)，yolo_filter_boxes()的输出，阈值过滤后的锚框的pc\n",
    "    boxes - tensor类型，维度为(None,4)，yolo_filter_boxes()的输出，阈值过滤后的锚框的(b_x, b_y, b_h, b_w)，已缩放到图像大小（见下文）\n",
    "    classes - tensor类型，维度为(None,)，yolo_filter_boxes()的输出，阈值过滤后的锚框的类别索引ci\n",
    "    max_boxes - 整数，预测的锚框数量的最大值\n",
    "    iou_threshold - 实数，交并比阈值。\n",
    "    \n",
    "    Returns:\n",
    "    scores - tensor类型，维度为(,None)，每个锚框的预测的可能值\n",
    "    boxes - tensor类型，维度为(4,None)，预测的锚框的坐标\n",
    "    classes - tensor类型，维度为(,None)，每个锚框的预测的分类\n",
    "    \n",
    "    Note: The \"None\" dimension of the output tensors has obviously to be less than max_boxes. Note also that this\n",
    "    function will transpose the shapes of scores, boxes, classes. This is made for convenience.\n",
    "    \"\"\"\n",
    "    \n",
    "    max_boxes_tensor = K.variable(max_boxes, dtype='int32')     # tensor to be used in tf.image.non_max_suppression()\n",
    "    K.get_session().run(tf.variables_initializer([max_boxes_tensor])) # initialize variable max_boxes_tensor\n",
    "    \n",
    "    # Use tf.image.non_max_suppression() to get the list of indices corresponding to boxes you keep\n",
    "    ### START CODE HERE ### (≈ 1 line)\n",
    "    nms_indices = tf.image.non_max_suppression(boxes, scores, max_boxes, iou_threshold) #内含iou\n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    #print(\"nms_indices.shape = \" + str(nms_indices.eval().shape))\n",
    "    # Use K.gather() to select only nms_indices from scores, boxes and classes\n",
    "    ### START CODE HERE ### (≈ 3 lines)\n",
    "    scores = K.gather(scores, nms_indices)\n",
    "    boxes = K.gather(boxes, nms_indices)\n",
    "    classes = K.gather(classes, nms_indices)\n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    return scores, boxes, classes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with tf.Session() as test_b:\n",
    "    scores = tf.random_normal([54,], mean=1, stddev=4, seed = 1)\n",
    "    boxes = tf.random_normal([54, 4], mean=1, stddev=4, seed = 1)\n",
    "    classes = tf.random_normal([54,], mean=1, stddev=4, seed = 1)\n",
    "    scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes)\n",
    "    print(\"scores[2] = \" + str(scores[2].eval()))\n",
    "    print(\"boxes[2] = \" + str(boxes[2].eval()))\n",
    "    print(\"classes[2] = \" + str(classes[2].eval()))\n",
    "    print(\"scores.shape = \" + str(scores.eval().shape))\n",
    "    print(\"boxes.shape = \" + str(boxes.eval().shape))\n",
    "    print(\"classes.shape = \" + str(classes.eval().shape))\n",
    "    print(\"scores = \" + str(scores.eval()))\n",
    "    print(\"boxes= \" + str(boxes.eval()))\n",
    "    print(\"classes= \" + str(classes.eval()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4 Wrapping up the filtering\n",
    "\n",
    "It's time to implement a function taking the output of the deep CNN (the 19x19x5x85 dimensional encoding) and filtering through all the boxes using the functions you've just implemented. \n",
    "\n",
    "**Exercise**: Implement `yolo_eval()` which takes the output of the YOLO encoding and filters the boxes using score threshold and NMS. There's just one last implementational detail you have to know. There're a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions (which we have provided): \n",
    "\n",
    "```python\n",
    "boxes = yolo_boxes_to_corners(box_xy, box_wh) \n",
    "```\n",
    "which converts the yolo box coordinates (x,y,w,h) to box corners' coordinates (x1, y1, x2, y2) to fit the input of `yolo_filter_boxes`\n",
    "```python\n",
    "boxes = scale_boxes(boxes, image_shape)\n",
    "```\n",
    "YOLO's network was trained to run on 608x608 images. If you are testing this data on a different size image--for example, the car detection dataset had 720x1280 images--this step rescales the boxes so that they can be plotted on top of the original 720x1280 image.  \n",
    "\n",
    "Don't worry about these two functions; we'll show you where they need to be called.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# GRADED FUNCTION: yolo_eval\n",
    "\n",
    "def yolo_eval(yolo_outputs, image_shape = (720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5):\n",
    "    \"\"\"\n",
    "      将YOLO编码的输出（很多锚框）转换为预测框以及它们的分数，框坐标和类。\n",
    "\n",
    "    参数：\n",
    "        yolo_outputs - 编码模型的输出（对于维度为（608,608,3）的图片），包含4个tensors类型的变量：\n",
    "                        box_confidence ： tensor类型，维度为(None, 19, 19, 5, 1)\n",
    "                        box_xy         ： tensor类型，维度为(None, 19, 19, 5, 2)\n",
    "                        box_wh         ： tensor类型，维度为(None, 19, 19, 5, 2)\n",
    "                        box_class_probs： tensor类型，维度为(None, 19, 19, 5, 80)\n",
    "        image_shape - tensor类型，维度为（2,），包含了输入的图像的维度，这里是(608.,608.)\n",
    "        max_boxes - 整数，预测的锚框数量的最大值\n",
    "        score_threshold - 实数，可能性阈值。\n",
    "        iou_threshold - 实数，交并比阈值。\n",
    "\n",
    "    返回：\n",
    "        scores - tensor类型，维度为(,None)，每个锚框的预测的可能值\n",
    "        boxes - tensor类型，维度为(4,None)，预测的锚框的坐标\n",
    "        classes - tensor类型，维度为(,None)，每个锚框的预测的分类\n",
    "    \"\"\"\n",
    "    \n",
    " ### START CODE HERE ### \n",
    "\n",
    "    # Retrieve outputs of the YOLO model (≈1 line)\n",
    "    box_confidence, box_xy, box_wh, box_class_probs = yolo_outputs[:]\n",
    "\n",
    "    # Convert boxes to be ready for filtering functions \n",
    "    # 将yolo锚框坐标（x，y，w，h）转换为角的坐标（x1，y1，x2，y2）以适应yolo_filter_boxes()的输入。\n",
    "    boxes = yolo_boxes_to_corners(box_xy, box_wh)\n",
    "\n",
    "    # Use one of the functions you've implemented to perform Score-filtering with a threshold of score_threshold (≈1 line)\n",
    "    # 可信度分值过滤\n",
    "    scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, score_threshold)\n",
    "\n",
    "    # Scale boxes back to original image shape.\n",
    "    # 缩放锚框，以适应原始图像\n",
    "    boxes = scale_boxes(boxes, image_shape)\n",
    "\n",
    "    # Use one of the functions you've implemented to perform Non-max suppression with a threshold of iou_threshold (≈1 line)\n",
    "    #使用非最大值抑制\n",
    "    scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes, max_boxes, iou_threshold)\n",
    "\n",
    "    ### END CODE HERE ###\n",
    "    \n",
    "    return scores, boxes, classes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with tf.Session() as test_b:\n",
    "    yolo_outputs = (tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1),\n",
    "                    tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),\n",
    "                    tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),\n",
    "                    tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1))\n",
    "    scores, boxes, classes = yolo_eval(yolo_outputs)\n",
    "    print(\"scores[2] = \" + str(scores[2].eval()))\n",
    "    print(\"boxes[2] = \" + str(boxes[2].eval()))\n",
    "    print(\"classes[2] = \" + str(classes[2].eval()))\n",
    "    print(\"scores.shape = \" + str(scores.eval().shape))\n",
    "    print(\"boxes.shape = \" + str(boxes.eval().shape))\n",
    "    print(\"classes.shape = \" + str(classes.eval().shape))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font color='blue'>\n",
    "**Summary for YOLO**:\n",
    "- Input image (608, 608, 3)\n",
    "- The input image goes through a CNN, resulting in a (19,19,5,85) dimensional output. \n",
    "- After flattening the last two dimensions, the output is a volume of shape (19, 19, 425):\n",
    "    - Each cell in a 19x19 grid over the input image gives 425 numbers. \n",
    "    - 425 = 5 x 85 because each cell contains predictions for 5 boxes, corresponding to 5 anchor boxes, as seen in lecture. \n",
    "    - 85 = 5 + 80 where 5 is because $(p_c, b_x, b_y, b_h, b_w)$ has 5 numbers, and and 80 is the number of classes we'd like to detect\n",
    "- You then select only few boxes based on:\n",
    "    - Score-thresholding: throw away boxes that have detected a class with a score less than the threshold\n",
    "    - Non-max suppression: Compute the Intersection over Union and avoid selecting overlapping boxes\n",
    "- This gives you YOLO's final output. \n",
    "\n",
    "对YOLO的总结：\n",
    "\n",
    "输入图像为(608,608,3)，先要通过一个CNN模型，返回一个(19,19,5,85)的数据。  \n",
    "在对最后两维降维之后，输出的维度变为了(19,19,425): 每个19x19的单元格拥有425个数字。  \n",
    "每个单元格拥有5个锚框，每个锚框由5个基本信息+80个分类预测构成。  \n",
    "85 = 5 + 85，其中5个基本信息是（pc,px,py,ph,pwpc,px,py,ph,pw）,剩下80就是80个分类的预测。  \n",
    "然后我们会根据以下规则选择锚框：  \n",
    "预测分数阈值：丢弃分数低于阈值的分类的锚框。  \n",
    "非最大值抑制：计算交并比，并避免选择重叠框。  \n",
    "最后给出YOLO的最终输出。  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 - Test YOLO pretrained model on images"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this part, you are going to use a pretrained model and test it on the car detection dataset. As usual, you start by **creating a session to start your graph**. Run the following cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sess = K.get_session()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.1 - Defining classes, anchors and image shape."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Recall that we are trying to detect 80 classes, and are using 5 anchor boxes. We have gathered the information about the 80 classes and 5 boxes in two files \"coco_classes.txt\" and \"yolo_anchors.txt\". Let's load these quantities into the model by running the next cell. \n",
    "\n",
    "The car detection dataset has 720x1280 images, which we've pre-processed into 608x608 images. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class_names = read_classes(\"model_data/coco_classes.txt\")\n",
    "anchors = read_anchors(\"model_data/yolo_anchors.txt\")\n",
    "image_shape = (720., 1280.)    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 - Loading a pretrained model\n",
    "\n",
    "Training a YOLO model takes a very long time and requires a fairly large dataset of labelled bounding boxes for a large range of target classes. You are going to load an existing pretrained Keras YOLO model stored in \"yolo.h5\". (These weights come from the official YOLO website, and were converted using a function written by Allan Zelener. References are at the end of this notebook. Technically, these are the parameters from the \"YOLOv2\" model, but we will more simply refer to it as \"YOLO\" in this notebook.) Run the cell below to load the model from this file.\n",
    "\n",
    "yolo.h5生成：\n",
    "\n",
    "git clone https://github.com/allanzelener/YAD2K.git\n",
    "\n",
    "cd YAD2K\n",
    "\n",
    "下载 yolo.weights和yolo.cfg放到文件夹，命令行执行：python yad2k.py yolo.cfg yolo.weights model_data/yolo.h5\n",
    "\n",
    "下载地址：http://pjreddie.com/media/files/yolo.weights\n",
    "\n",
    "https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolo.cfg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "yolo_model = load_model(\"model_data/yolo.h5\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This loads the weights of a trained YOLO model. Here's a summary of the layers your model contains."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "yolo_model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note**: On some computers, you may see a warning message from Keras. Don't worry about it if you do--it is fine.\n",
    "\n",
    "**Reminder**: this model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure (2)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.3 - Convert output of the model to usable bounding box tensors\n",
    "\n",
    "The output of `yolo_model` is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. The following cell does that for you."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将模型的输出转换为边界框\n",
    "yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You added `yolo_outputs` to your graph. This set of 4 tensors is ready to be used as input by your `yolo_eval` function."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.4 - Filtering boxes\n",
    "\n",
    "`yolo_outputs` gave you all the predicted boxes of `yolo_model` in the correct format. You're now ready to perform filtering and select only the best boxes. Lets now call `yolo_eval`, which you had previously implemented, to do this. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#过滤并仅选择最佳的锚框\n",
    "scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.5 - Run the graph on an image\n",
    "\n",
    "Let the fun begin. You have created a (`sess`) graph that can be summarized as follows:\n",
    "\n",
    "1. <font color='purple'> yolo_model.input </font> is given to `yolo_model`. The model is used to compute the output <font color='purple'> yolo_model.output </font>\n",
    "2. <font color='purple'> yolo_model.output </font> is processed by `yolo_head`. It gives you <font color='purple'> yolo_outputs </font>\n",
    "3. <font color='purple'> yolo_outputs </font> goes through a filtering function, `yolo_eval`. It outputs your predictions: <font color='purple'> scores, boxes, classes </font>\n",
    "\n",
    "**Exercise**: Implement predict() which runs the graph to test YOLO on an image.\n",
    "You will need to run a TensorFlow session, to have it compute `scores, boxes, classes`.\n",
    "\n",
    "The code below also uses the following function:\n",
    "```python\n",
    "image, image_data = preprocess_image(\"images/\" + image_file, model_image_size = (608, 608))\n",
    "```\n",
    "which outputs:\n",
    "- image: a python (PIL) representation of your image used for drawing boxes. You won't need to use it.\n",
    "- image_data: a numpy-array representing the image. This will be the input to the CNN.\n",
    "\n",
    "**Important note**: when a model uses BatchNorm (as is the case in YOLO), you will need to pass an additional placeholder in the feed_dict {K.learning_phase(): 0}."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict(sess, image_file, is_show_info=True, is_plot=True):\n",
    "    \"\"\"\n",
    "    运行存储在sess的计算图以预测image_file的边界框，打印出预测的图与信息。\n",
    "\n",
    "    参数：\n",
    "        sess - 包含了YOLO计算图的TensorFlow/Keras的会话。\n",
    "        image_file - 存储在images文件夹下的图片名称\n",
    "    返回：\n",
    "        out_scores - tensor类型，维度为(None,)，锚框的预测的可能值。\n",
    "        out_boxes - tensor类型，维度为(None,4)，包含了锚框位置信息。\n",
    "        out_classes - tensor类型，维度为(None,)，锚框的预测的分类索引。 \n",
    "    \"\"\"\n",
    "    #图像预处理\n",
    "    image, image_data = preprocess_image(\"images/\" + image_file, model_image_size = (608, 608))\n",
    "\n",
    "    #运行会话并在feed_dict中选择正确的占位符.\n",
    "    out_scores, out_boxes, out_classes = sess.run([scores, boxes, classes], feed_dict = {yolo_model.input:image_data, K.learning_phase(): 0})\n",
    "\n",
    "    #打印预测信息\n",
    "    if is_show_info:\n",
    "        print(\"在\" + str(image_file) + \"中找到了\" + str(len(out_boxes)) + \"个锚框。\")\n",
    "\n",
    "    #指定要绘制的边界框的颜色\n",
    "    colors = generate_colors(class_names)\n",
    "\n",
    "    #在图中绘制边界框\n",
    "    draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)\n",
    "\n",
    "    #保存已经绘制了边界框的图\n",
    "    image.save(os.path.join(\"out\", image_file), quality=100)\n",
    "\n",
    "    #打印出已经绘制了边界框的图\n",
    "    if is_plot:\n",
    "        output_image = scipy.misc.imread(os.path.join(\"out\", image_file))\n",
    "        plt.imshow(output_image)\n",
    "\n",
    "    return out_scores, out_boxes, out_classes\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Run the following cell on the \"test.jpg\" image to verify that your function is correct."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "out_scores, out_boxes, out_classes = predict(sess, \"test.jpg\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "<font color='blue'>\n",
    "**What you should remember**:\n",
    "- YOLO is a state-of-the-art object detection model that is fast and accurate\n",
    "- It runs an input image through a CNN which outputs a 19x19x5x85 dimensional volume. \n",
    "- The encoding can be seen as a grid where each of the 19x19 cells contains information about 5 boxes.\n",
    "- You filter through all the boxes using non-max suppression. Specifically: \n",
    "    - Score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes\n",
    "    - Intersection over Union (IoU) thresholding to eliminate overlapping boxes\n",
    "- Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as lot of computation, we used previously trained model parameters in this exercise. If you wish, you can also try fine-tuning the YOLO model with your own dataset, though this would be a fairly non-trivial exercise. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(1,121):\n",
    "\n",
    "    #计算需要在前面填充几个0\n",
    "    num_fill = int( len(\"0000\") - len(str(1))) + 1\n",
    "    #对索引进行填充\n",
    "    filename = str(i).zfill(num_fill) + \".jpg\"\n",
    "    print(\"当前文件：\" + str(filename))\n",
    "\n",
    "    #开始绘制，不打印信息，不绘制图\n",
    "    out_scores, out_boxes, out_classes = predict(sess, filename,is_show_info=False,is_plot=False)\n",
    "\n",
    "\n",
    "\n",
    "print(\"绘制完成！\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**References**: The ideas presented in this notebook came primarily from the two YOLO papers. The implementation here also took significant inspiration and used many components from Allan Zelener's github repository. The pretrained weights used in this exercise came from the official YOLO website. \n",
    "- Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi - [You Only Look Once: Unified, Real-Time Object Detection](https://arxiv.org/abs/1506.02640) (2015)\n",
    "- Joseph Redmon, Ali Farhadi - [YOLO9000: Better, Faster, Stronger](https://arxiv.org/abs/1612.08242) (2016)\n",
    "- Allan Zelener - [YAD2K: Yet Another Darknet 2 Keras](https://github.com/allanzelener/YAD2K)\n",
    "- The official YOLO website (https://pjreddie.com/darknet/yolo/) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Car detection dataset**:\n",
    "<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by/4.0/88x31.png\" /></a><br /><span xmlns:dct=\"http://purl.org/dc/terms/\" property=\"dct:title\">The Drive.ai Sample Dataset</span> (provided by drive.ai) is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by/4.0/\">Creative Commons Attribution 4.0 International License</a>. We are especially grateful to Brody Huval, Chih Hu and Rahul Patel for collecting and providing this dataset. "
   ]
  }
 ],
 "metadata": {
  "coursera": {
   "course_slug": "convolutional-neural-networks",
   "graded_item_id": "OMdut",
   "launcher_item_id": "bbBOL"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
